import * as React from 'react'
import { authService, type User } from '@/services/authService'

// User 类型已从 authService 导入

type AuthContextValue = {
    user: User | null
    token: string | null
    login: (params: { phone: string; password: string }) => Promise<void>
    register: (params: { name: string; phone: string; password: string; password_confirmation: string }) => Promise<void>
    updateProfile: (params: { name?: string; avatar?: File }) => Promise<void>
    logout: () => void
    isLoading: boolean
}

const AuthContext = React.createContext<AuthContextValue | undefined>(undefined)

export function AuthProvider({ children }: { children: React.ReactNode }) {
    const [user, setUser] = React.useState<User | null>(() => authService.getUser())
    const [token, setToken] = React.useState<string | null>(() => authService.getToken())
    const [isLoading, setIsLoading] = React.useState(false)

    React.useEffect(() => {
        if (!token) return
        
        // 如果有token但没有用户信息，尝试获取用户信息
        if (!user) {
            const fetchUserInfo = async () => {
                try {
                    const userData = await authService.fetchUserInfo()
                    setUser(userData)
                } catch (error) {
                    // Token无效或过期，清理登录状态
                    setToken(null)
                    setUser(null)
                }
            }
            
            fetchUserInfo()
        }
    }, [token, user])

    const login = React.useCallback(async ({ phone, password }: { phone: string; password: string }) => {
        setIsLoading(true)
        try {
            const data = await authService.login(phone, password)
            
            if (data.success && data.data?.token && data.data?.user) {
                setToken(data.data.token)
                setUser(data.data.user)
            } else {
                throw new Error('登录失败')
            }
        } catch (error) {
            throw error
        } finally {
            setIsLoading(false)
        }
    }, [])

    const register = React.useCallback(async ({ name, phone, password, password_confirmation }: { name: string; phone: string; password: string; password_confirmation: string }) => {
        setIsLoading(true)
        try {
            const data = await authService.register(name, phone, password, password_confirmation)
            
            if (data.success && data.data?.token && data.data?.user) {
                setToken(data.data.token)
                setUser(data.data.user)
            } else {
                throw new Error('注册失败')
            }
        } catch (error) {
            throw error
        } finally {
            setIsLoading(false)
        }
    }, [])

    const updateProfile = React.useCallback(async ({ name, avatar }: { name?: string; avatar?: File }) => {
        if (!token) throw new Error('请先登录')
        
        setIsLoading(true)
        try {
            const updatedUser = await authService.updateProfile({ name, avatar })
            setUser(updatedUser)
        } catch (error) {
            throw error
        } finally {
            setIsLoading(false)
        }
    }, [token])

    const logout = React.useCallback(() => {
        authService.logout()
        setToken(null)
        setUser(null)
    }, [])

    return (
        <AuthContext.Provider value={{ user, token, login, register, updateProfile, logout, isLoading }}>{children}</AuthContext.Provider>
    )
}

export const useAuth = () => {
    const ctx = React.useContext(AuthContext)
    if (!ctx) throw new Error('useAuth must be used within AuthProvider')
    return ctx
}


